<?php

namespace App\Admin\Extensions\Tools;

use App\Handlers\WithdrawalHandler;
use Dcat\Admin\Grid\BatchAction;
use Illuminate\Http\Request;
use App\Models\Withdrawal;

// 批量 审核
class BatchAudit extends BatchAction
{
    protected $action;

    // 注意action的构造方法参数一定要给默认值

    /***
     * BatchAudit constructor.
     * @param  null  $title   提示内容
     * @param  int   $action  操作方式 1通过，2驳回
     */
    public function __construct($title = '...', $action = 1)
    {
        $this->title  = $title;
        $this->action = $action;
    }

    // 确认弹窗信息
    public function confirm()
    {
        return '您确定要 <span style="color:red;">'.$this->title.'</span>&nbsp;已选中的内容吗？';
    }

    // 处理请求
    public function handle(Request $request)
    {
        // 获取选中的文章ID数组
        $keys = $this->getKey();

        // 获取请求参数
        $action = $request->get('action');

        foreach (Withdrawal::find($keys) as $post) {
            if ($post->sp_status == 0) {
                $post->sp_status = $action;
                $message = $action == 1 ? '驳回成功' : '通过成功';
                \DB::beginTransaction();
                if ($post->save()) {
                    if ($post->sp_status == 1) {// 驳回
                        try {
                            WithdrawalHandler::refundUserMoney($post, '审核不通过');
                            \DB::commit();
                        }catch (\Exception $e){
                            \DB::rollBack();
                            return $this->response()->error('数据有误不可投出，请驳回')->refresh();
                        }
                    } elseif ($post->sp_status == 2) {// 通过
                        try {
                            WithdrawalHandler::upUserCommission($post, '审核通过');
                            \DB::commit();
                        }catch (\Exception $e){
                            \DB::rollBack();
                            return $this->response()->error('数据有误不可投出，请驳回')->refresh();
                        }
                    }
                }
            }
        }

        return $this->response()->success($message)->refresh();
    }

    // 设置请求参数
    public function parameters()
    {
        return [
            'action' => $this->action,
        ];
    }
}
